﻿package cn.itlaobing.servlet;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;

import javax.servlet.ServletConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.itlaobing.annotation.AnnotationMapping;

/** 
 * ClassName: BaseServlet <br/> 
 * Function: 实现现阶段的框架雏形，进行一个servlet的进一步优化 <br/> 
 * date: 2017年10月31日 下午9:48:00 <br/> 
 * 
 * @author 苏积钰 1
 * @version  
 * @since JDK 1.8 
 */
public class BaseServlet extends HttpServlet     {
	HashMap<String, Method> map=new HashMap<String,Method>();
	@Override
	public void init(ServletConfig config)  {
		Class clz=this.getClass();
		WebServlet ws=(WebServlet) clz.getAnnotation(WebServlet.class);
		System.out.println(ws.value()[0]);
		
		
		Method[] m=clz.getDeclaredMethods();
		for (Method method : m) {
			if(method.isAnnotationPresent(AnnotationMapping.class))
			{
			String methodUrl=method.getAnnotation(AnnotationMapping.class).value();
			String fullUrl=ws.value()[0].replace("/*", "")+methodUrl;
				map.put(fullUrl, method);
			}
		}
	}
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp)  {
		String url=req.getRequestURI();
		Method m=map.get(url);
		try {
			if(m==null)
			{
				
					resp.sendError(404,"请求路径错误");
					return;
				
			}
			m.invoke(this, req,resp);
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
